package com.asyf.nacosconfig.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.Callable;

/**
 * Nacos Data ID 标准格式如下:
 * ${prefix}-${spring.profiles.active}.${file-extension}
 * prefix ：默认为 spring.application.name 的值
 * spring.profiles.active：该案例为空，一般指定 dev test 等环境配置
 * file-extension：配置内容格式
 * <p>
 * 配置优先级
 * 配置中心 > 命令行参数 > 本地application.yml > 本地bootstrap.yml
 */
@Api(tags = "示例接口")
@RestController
@RequestMapping(value = "/")
@Slf4j
@RefreshScope//允许在运行时动态刷新 Bean 的 Scope 实现。
public class DemoController {

    @Value("${data.name}")
    private String name;

    @ApiOperation(value = "测试接口")
    @RequestMapping(value = "/demo", method = RequestMethod.GET)
    public String test() throws InterruptedException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String appid = request.getHeader("appid");
        log.info("appid:{}", appid);
        Thread.sleep(30000);
        return "nacos配置中心：" + name + "    appid:" + appid;
    }

    //只有返回callable才会超时
    @GetMapping("/timeOutTest")
    @ApiOperation("超时测试")
    public Callable<String> jkCallable() {
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(100000); //this will cause a timeout
                return "接口Callable测试";
            }
        };
    }

}
